package com.cssw.fyzb.tps.api.vod;

import com.cssw.fyzb.tps.cache.Cache;
import com.cssw.fyzb.tps.cache.CacheKeys;
import com.cssw.fyzb.tps.cache.Fetcher;
import com.cssw.fyzb.tps.client.VodClient;
import com.cssw.fyzb.tps.model.vo.UploadSigVo;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Property;
import com.ydn.appserver.annotations.Result;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Feng Chen
 */
@Function(description = "获取上传签名", result = @Result(properties = {
        @Property(name = "signature", type = Type.String, description = "签名"),
        @Property(name = "currentTimeStamp", type = Type.String, description = "当前时间戳"),
        @Property(name = "expireTimeStamp", type = Type.String, description = "失效时间戳"),
}))
@Component
public class GetUploadSig implements Action {

    @Autowired
    private VodClient vodClient;

    private static final Logger logger = LoggerFactory.getLogger(GetUploadSig.class);

    @Override
    public Response execute(Request request) throws Exception {
        // 获取任务编号
        try {

            UploadSigVo vo = Cache.get(CacheKeys.uploadSigKey(), new Fetcher<UploadSigVo>() {
                @Override
                public UploadSigVo fetch() {
                    return vodClient.uploadSig();
                }
            });

            if (vo != null && System.currentTimeMillis() / 1000 >= vo.getExpireTimeStamp()) {
                vo = Cache.get(CacheKeys.uploadSigKey(), new Fetcher<UploadSigVo>() {
                    @Override
                    public UploadSigVo fetch() {
                        return vodClient.uploadSig();
                    }
                }, true);
            }

            return Response.success().put("data", vo);
        } catch (Exception e) {
            logger.error("", e);
        }

        return Response.fail("操作异常");
    }

}
